package com.woyao;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.woyao.core.model.Area;
import com.woyao.core.model.AreaResponse;
import com.woyao.core.service.AreaService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;

public class ConfirmLocation extends AppCompatActivity {

    LinearLayoutManager allLayoutManager = null;
    private RecyclerView alllist = null;
    private SingleTreeAdapter allAdapter;

    Boolean changed = false;
    ProgressDialog progressDialog;

    private String curLocationNo="";

    ArrayList<String> parents = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_confirm_location);

        Toolbar toolbar = (Toolbar) findViewById(R.id.confirmLocation_toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        //       ab.setHomeAsUpIndicator(R.drawable.icon_menu); // set a custom icon for the default home button
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout
//        ab.setDisplayShowTitleEnabled(false); // disable the default title element
        this.setTitle("选择所在地区");


        alllist = (RecyclerView) findViewById(R.id.id_confirmLocation_list);
        allLayoutManager = new LinearLayoutManager(this);
        allLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        alllist.setLayoutManager(allLayoutManager);
        alllist.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        TextView roottitle = (TextView) findViewById(R.id.confirmLocation_roottitle);

        roottitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                loadLocations("");
            }
        });

        this.setTitle("请选择所在地区");

        loadLocations("");



    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();

        intent.putExtra("no",curLocationNo);
        intent.putExtra("name",Common.listToString(parents).replace(",","/"));

        setResult(0, intent);
        finish();
        return true;
    }

    private void loadLocations( final  String curLocation){

        progressDialog = new ProgressDialog(ConfirmLocation.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("加载···");
        progressDialog.show();

        if ( curLocation.length() <=1) {
            parents.clear();
        }
        AsyncTask<Void,Void,AreaResponse> task =
                new AsyncTask<Void, Void, AreaResponse>() {
                    @Override
                    protected AreaResponse doInBackground(Void... params) {
                        AreaService svc = ServiceFactory.get(AreaService.class);
                        Call<AreaResponse> responseCall = svc.getArea(curLocation,WoyaoooApplication.userId,"yes","confirm");
                        try {
                            AreaResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                    @Override
                    protected void onPostExecute(final AreaResponse response) {
                        if (response.isSuccess()){
                            renderAll(response.getContent());
                        }else{
                            Common.alert( ConfirmLocation.this,response.getMessage());
                        }
                        progressDialog.dismiss();
                    }

                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute();
    }


    private void renderAll(ArrayList<Area> areas){

        ArrayList<Map<String,String>> mapList = new ArrayList<>();

        for(Area ar : areas){
            HashMap<String,String> map = new HashMap<>();
            map.put("no", ar.getId() +"");
            map.put("name", ar.getName());
            map.put("description", "");
            map.put("childs", ar.getChilds() +"");
            mapList.add(map);
        }
        allAdapter = new SingleTreeAdapter(this,  mapList );

        allAdapter.setChangedHandler(new SingleTreeAdapter.Changed() {
            @Override
            public void itemSelected(Map<String, String> one) {
                Intent intent = new Intent();
                parents.add( one.get("name"));

                curLocationNo = one.get("no");

                intent.putExtra("no",one.get("no"));
                intent.putExtra("name",Common.listToString(parents).replace(",","/"));

                setResult(666, intent);
                finish();

            }

            @Override
            public void itemGetChildren(Map<String, String> one) {
                loadLocations( one.get("no"));
                parents.add( one.get("name"));
                curLocationNo = one.get("no");

            }
        });
        alllist.setAdapter(allAdapter);

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();

            intent.putExtra("no",curLocationNo);
            intent.putExtra("name",Common.listToString(parents).replace(",","/"));

            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

}

